import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import rigister from '../views/rigister.vue'
import index from '../views/index.vue'

import users from '../views/users/users.vue'
import Roles from '../views/rights/Roles.vue'
import Home from '../views/home/Home.vue'
import Rights from '../views/rights/Rights.vue'
import goods from '../views/products/goods.vue'
import categories from '../views/products/categories.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/index' },
  {
    path: '/index',
    component: index,
    children: [
      { path: '', component: Home },
      { path: '/users', component: users },
      { path: '/roles', component: Roles },
      { path: '/rights', component: Rights },
      { path: '/goods', component: goods },
      { path: '/categories', component: categories }
    ]
  },
  { path: '/login', component: Login },
  { path: '/rigister', component: rigister }
]

const router = new VueRouter({
  routes
})

// to 到哪去
// from 从哪来
// next 是否放行  next() 放行    next('/login') 拦截到登录
// 如果准备去登录, 不需要拦截
// 如果已经登录过了, 有token, 不需要拦截
// 如果不是去登陆, 且没有 token, 拦截到登录页
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})

export default router
